package com.bzframework.pro.authorize.web;

import com.bzframework.pro.authorize.annotation.Authorization;
import com.bzframework.pro.authorize.context.ReactiveUserTokenContextHolder;
import com.bzframework.pro.authorize.entity.UserEntity;
import com.bzframework.pro.authorize.service.UserService;
import com.bzframework.pro.authorize.strategy.login.LoginStrategyExecutor;
import com.bzframework.pro.authorize.token.UserToken;
import com.bzframework.pro.authorize.token.manager.UserTokenManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @Author bingzhong
 * @Date 2024/11/27 17:28
 * @Description
 */
@Tag(name = "用户授权")
@RestController
@RequestMapping("/authorize")
@RequiredArgsConstructor
public class AuthorizationController {

    private final UserService userService;

    private final UserTokenManager userTokenManager;

    private final LoginStrategyExecutor loginStrategyExecutor;

    @Authorization(ignore = true)
    @PostMapping("/register")
    @Operation(summary = "注册用户")
    public Mono<Boolean> register() {
        return Mono.just(true);
    }

    @Authorization(ignore = true)
    @PostMapping("/login")
    @Operation(summary = "账号密码登录")
    public Mono<UserToken> loginByAccountPassword(@RequestBody Mono<Map<String, Object>> parameter) {
        return parameter.flatMap(loginStrategyExecutor::doLogin);
    }

    @DeleteMapping("/logout")
    @Operation(summary = "退出登录")
    public Mono<Long> logout() {
        return ReactiveUserTokenContextHolder.get()
                .map(UserToken::getToken)
                .flatMap(userTokenManager::removeToken);
    }

    @GetMapping("/me")
    @Operation(summary = "获取用户信息")
    public Mono<UserEntity> me() {
        return ReactiveUserTokenContextHolder.get()
                .map(UserToken::getUserId)
                .flatMap(userService::getSafetyUser);
    }

}
